package nl.infodation.emr.pricingservice.ui;

import net.atontech.vaadin.ui.numericfield.NumericField;
import nl.infodation.emr.pricingservice.business.BusinessFactory;
import nl.infodation.emr.pricingservice.data.AdvantageItem;
import nl.infodation.emr.pricingservice.data.ProductSelection;
import nl.infodation.emr.pricingservice.entity.DomainRule;
import nl.infodation.emr.pricingservice.entity.Environment;
import nl.infodation.emr.pricingservice.ui.component.IView;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.BooleanUtil;
import nl.infodation.emr.utility.Constants;
import nl.infodation.emr.utility.CreateElementOnGui;
import nl.infodation.emr.utility.CreateElementOnGui.StyleNameCss;
import nl.infodation.emr.utility.DateTimeUtil;
import nl.infodation.emr.utility.ListenerUtil;
import nl.infodation.emr.utility.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.Notification;

public class AdvantageView extends CustomComponent implements IView,
		ClickListener {

	private CustomLayout advantageCustomLayout;

	private Label lblGift;
	private Label lblShipping;
	private Label lblOrder;
	private Label lblRuleName;
	private Label lblBusinessLine;
	private Label lblRule;
	private Label lblBusiness;
	private Label lblEnvironmentName;
	private Button btnCancel;
	private Button btnSave;
	private NumericField tfCheapestFromFamilyDiscount;
	private CheckBox chbOrderShippingFee;
	private NumericField tfOrderShippingFee;
	private CheckBox chbShippingDiscountPercent;
	private NumericField tfShippingDiscountPercent;
	private NumericField tfOrderDiscountPercent;
	private CheckBox chbOrderDiscountPercent;
	private TextField tfCategory;
	private NumericField tfRefco;
	private NumericField tfOfOrderOffer;
	private CheckBox chbAddRefco;
	private CheckBox chbAddRefcoOfOrder;
	private NumericField tfFromSalesupportOffer;
	private NumericField tfFamily;
	private NumericField tfDiscount;
	private CheckBox chbAddRefcoFromSalesupport;
	private CheckBox chbDiscountForCheapestRefco;
	private CheckBox chbOrderProposeDiscount;

	private NumericField tfOrderlineShippingDiscountPerc;
	private CheckBox chbOrderlineShippingFeesDiscountPerc;

	private CheckBox chbOrderlineDiscountPerc;
	private NumericField tfOrderlineDiscountPerc;

	private CheckBox chbOrderlineDiscount;
	private NumericField tfOrderlineDiscount;

	private CheckBox chbOrderLineSellingPrice;
	private NumericField tfSellingPrice;

	private CheckBox chbOrderLineShippingFee;
	private NumericField tfOrderLineShippingFee;

	private Button btnSelect;
	private TextField tfProductCode;
	private TextField tfProductId;
	private NumericField tfItemId;
	private TextField tfCommercialRef;
	private CheckBox chbGift;

	public AdvantageView(MainView parentView) {
		this.parentView = parentView;
		initLayout();
	}

	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory
			.getLogger(AdvantageView.class);
	private MainView parentView;

	@Override
	public void initLayout() {
		advantageCustomLayout = new CustomLayout("AdvantageDefinition");
		buildMainLayout();
		setCaptionForMultiLanguage();
		addListener();
		initEnvironmentHeader();
		setCompositionRoot(advantageCustomLayout);
	}

	private void initEnvironmentHeader() {
		Environment env = BusinessFactory.getSystemBusiness().getEnvironment(
				SessionData.getEnvironment());
		if (env != null) {
			String envName = env.getEnvironmentName() + " Environment";
			lblEnvironmentName.setValue(envName);
		}
	}

	public void setBinding(Property busProperty, Property ruleProperty,
			Property envProperty) {
		lblBusinessLine.setPropertyDataSource(busProperty);
		lblRuleName.setPropertyDataSource(ruleProperty);
		lblEnvironmentName.setPropertyDataSource(envProperty);
	}

	private boolean hasNoChoice() {
		// Gift
		if (((boolean) chbGift.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfCommercialRef
						.getValue())
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfItemId.getValue())) {
			return false;

			// Shipping fees
		} else if (((boolean) this.chbOrderShippingFee.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfOrderShippingFee
						.getValue())) {
			return false;

		} else if (((boolean) this.chbOrderLineShippingFee.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfOrderLineShippingFee
								.getValue())) {
			return false;

		} else if (((boolean) this.chbShippingDiscountPercent.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfShippingDiscountPercent
								.getValue())) {
			return false;

			// Order
		} else if (((boolean) this.chbOrderProposeDiscount.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfDiscount
						.getValue())) {
			return false;

		} else if (((boolean) this.chbOrderLineSellingPrice.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfSellingPrice
						.getValue())) {
			return false;

		} else if (((boolean) this.chbOrderlineDiscountPerc.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfOrderlineDiscountPerc
								.getValue())) {
			return false;

		} else if (((boolean) this.chbOrderlineDiscount.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfOrderlineDiscount
						.getValue())) {
			return false;

		} else if (((boolean) this.chbOrderlineShippingFeesDiscountPerc
				.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfOrderlineShippingDiscountPerc
								.getValue())) {
			return false;

		} else if (((boolean) this.chbDiscountForCheapestRefco.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfFamily.getValue())) {
			return false;

		} else if (((boolean) this.chbAddRefcoFromSalesupport.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfFromSalesupportOffer
								.getValue())
				&& !StringUtil.isEmptyOrBlank((String) this.tfCategory
						.getValue())) {
			return false;

		} else if (((boolean) this.chbAddRefcoOfOrder.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfOfOrderOffer
						.getValue())) {
			return false;

		} else if (((boolean) this.chbAddRefco.getValue()) == true
				&& !StringUtil.isEmptyOrBlank((String) this.tfRefco.getValue())) {
			return false;

		} else if (((boolean) this.chbOrderDiscountPercent.getValue()) == true
				&& !StringUtil
						.isEmptyOrBlank((String) this.tfOrderDiscountPercent
								.getValue())) {
			return false;

		}
		return true;
	}

	public boolean validate() {
		if (hasNoChoice()) {
			if (parentView.getCurrentView() instanceof AdvantageView) {
				getWindow()
						.showNotification(
								SessionData
										.getI18N()
										.getMessage(
												Constants.ERROR_CONSTRAINT_IN_ADVANTAGE_VIEW_MESSAGE),
								Notification.TYPE_WARNING_MESSAGE);
			}
			return false;
		}
		return true;
	}

	private void setCaptionForMultiLanguage() {
		lblBusiness.setValue(SessionData.getI18N().getMessage(
				Constants.BUSINESS_LABEL));
		lblRule.setValue(SessionData.getI18N().getMessage(Constants.RULE_LABEL));

		lblGift.setValue(SessionData.getI18N().getMessage(Constants.GIFT_PANEL));
		chbGift.setCaption(SessionData.getI18N().getMessage(
				Constants.GIFT_CHECKBOX));
		tfProductCode.setCaption(SessionData.getI18N().getMessage(
				Constants.PRODUCT_CODE_TEXTFIELD));
		tfProductId.setCaption(SessionData.getI18N().getMessage(
				Constants.PRODUCT_ID_TEXTFIELD));
		tfCommercialRef.setCaption(SessionData.getI18N().getMessage(
				Constants.COMMERCIAL_REF_TEXTFIELD));
		tfItemId.setCaption(SessionData.getI18N().getMessage(
				Constants.ITEM_ID_TEXTFIELD));
		// pnlControl.setCaption(SessionData.getI18N().getMessage(Constants.CONTROL_PANEL));
		btnSave.setCaption(SessionData.getI18N().getMessage(
				Constants.SAVE_BUTTON));
		btnCancel.setCaption(SessionData.getI18N().getMessage(
				Constants.CANCEL_BUTTON));
		btnSelect.setCaption(SessionData.getI18N().getMessage(
				Constants.SELECT_BUTTON));

		lblShipping.setValue(SessionData.getI18N().getMessage(
				Constants.SHIPPING_PANEL));
		chbOrderShippingFee.setCaption(SessionData.getI18N().getMessage(
				Constants.ORDER_SHIPPING_FEE_CHECKBOX));
		chbShippingDiscountPercent.setCaption(SessionData.getI18N().getMessage(
				Constants.SHIPPING_DISCOUNT_PERCENT_CHECKBOX));

		chbOrderLineShippingFee.setCaption(SessionData.getI18N().getMessage(
				Constants.ORDERLINE_SHIPPING_FEE_CHECKBOX));

		setOrderLineDiscountState(parentView.getPriceType());

		lblOrder.setValue(SessionData.getI18N().getMessage(
				Constants.ORDER_PANEL));
		chbOrderProposeDiscount.setCaption(SessionData.getI18N().getMessage(
				Constants.ORDER_PROPOSE_DISCOUNT_CHECKBOX));
		chbOrderLineSellingPrice.setCaption(SessionData.getI18N().getMessage(
				Constants.ORDERLINE_SELLING_PRICE_CHECKBOX));
		chbDiscountForCheapestRefco.setCaption(SessionData.getI18N()
				.getMessage(Constants.DISCOUNT_FOR_CHEAPEST_REFCO_CHECKBOX));
		chbAddRefcoFromSalesupport.setCaption(SessionData.getI18N().getMessage(
				Constants.ADD_REFCO_FROM_SALESUPPORT_CHECKBOX));
		chbAddRefcoOfOrder.setCaption(SessionData.getI18N().getMessage(
				Constants.ADD_REFCO_OF_ORDER_CHECKBOX));
		chbAddRefco.setCaption(SessionData.getI18N().getMessage(
				Constants.ADD_REFCO_CHECKBOX));
		chbOrderDiscountPercent.setCaption(SessionData.getI18N().getMessage(
				Constants.ORDER_DISCOUNT_PERCENT_CHECKBOX));
		chbOrderlineShippingFeesDiscountPerc.setCaption(SessionData.getI18N()
				.getMessage(Constants.ORDER_LINE_SHIPPING_DISCOUNT));
	}

	private void addListener() {
		btnSelect.addListener((ClickListener) this);
		btnSave.addListener((ClickListener) this);
		btnCancel.addListener((ClickListener) this);

		lblBusinessLine.setImmediate(true);
		lblBusinessLine.addListener(new ValueChangeListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Property p = event.getProperty();
				String bussinesLine = p.getValue().toString();
				setAdvantageDisplay(bussinesLine);
			}
		});

		ListenerUtil.addClickListenerToCheckBox(chbGift, (ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderShippingFee,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderLineShippingFee,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderProposeDiscount,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderLineSellingPrice,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderlineDiscountPerc,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderlineDiscount,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(
				chbOrderlineShippingFeesDiscountPerc, (ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbDiscountForCheapestRefco,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbAddRefcoFromSalesupport,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbAddRefcoOfOrder,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbAddRefco,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbShippingDiscountPercent,
				(ClickListener) this);

		ListenerUtil.addClickListenerToCheckBox(chbOrderDiscountPercent,
				(ClickListener) this);
	}

	private void setFieldEnable() {
		CreateElementOnGui.setFieldsEnable(chbGift, tfProductCode, tfProductId,
				tfCommercialRef, tfItemId);

		CreateElementOnGui.setFieldsEnable(chbOrderShippingFee,
				tfOrderShippingFee);

		CreateElementOnGui.setFieldsEnable(chbShippingDiscountPercent,
				tfShippingDiscountPercent);

		CreateElementOnGui.setFieldsEnable(chbOrderDiscountPercent,
				tfOrderDiscountPercent);

		CreateElementOnGui.setFieldsEnable(chbOrderProposeDiscount, tfDiscount);

		// Order Line
		CreateElementOnGui.setFieldsEnable(chbOrderLineSellingPrice,
				tfSellingPrice);

		CreateElementOnGui.setFieldsEnable(chbOrderlineDiscountPerc,
				tfOrderlineDiscountPerc);

		CreateElementOnGui.setFieldsEnable(chbOrderlineDiscount,
				tfOrderlineDiscount);

		CreateElementOnGui.setFieldsEnable(chbOrderLineShippingFee,
				tfOrderLineShippingFee);

		CreateElementOnGui.setFieldsEnable(
				chbOrderlineShippingFeesDiscountPerc,
				tfOrderlineShippingDiscountPerc);

		// Other
		CreateElementOnGui.setFieldsEnable(chbDiscountForCheapestRefco,
				tfFamily, tfCheapestFromFamilyDiscount);

		CreateElementOnGui.setFieldsEnable(chbAddRefcoFromSalesupport,
				tfFromSalesupportOffer, tfCategory);

		CreateElementOnGui.setFieldsEnable(chbAddRefcoOfOrder, tfOfOrderOffer);

		CreateElementOnGui.setFieldsEnable(chbAddRefco, tfRefco);

	}

	private void getContentValuesFromCheckBoxes(AdvantageItem item) {
		// All Checkbox
		item.setGiftEnable(CreateElementOnGui.getValueCheckBox(chbGift));
		item.setOrderShippingFeeEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderShippingFee));
		item.setOrderlineShippingFeeEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderLineShippingFee));
		item.setOrderProposeDiscountEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderProposeDiscount));
		item.setOrderlineSellingPriceEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderLineSellingPrice));
		item.setDiscountForCheapestRefcoEnable(CreateElementOnGui
				.getValueCheckBox(chbDiscountForCheapestRefco));
		item.setAddRefcoFromSalesupportEnable(CreateElementOnGui
				.getValueCheckBox(chbAddRefcoFromSalesupport));
		item.setAddRefcoOfOrderEnable(CreateElementOnGui
				.getValueCheckBox(chbAddRefcoOfOrder));
		item.setAddRefcoEnable(CreateElementOnGui.getValueCheckBox(chbAddRefco));
		item.setShippingDiscountPercentEnable(CreateElementOnGui
				.getValueCheckBox(chbShippingDiscountPercent));
		item.setOrderDiscountPercentEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderDiscountPercent));
		item.setOrderlineDiscountPercentageEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderlineDiscountPerc));
		item.setOrderlineDiscountEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderlineDiscount));
		item.setOrderlineShippingFeeDiscountPercentageEnable(CreateElementOnGui
				.getValueCheckBox(chbOrderlineShippingFeesDiscountPerc));
	}

	private void getContentValuesFromTextFields(AdvantageItem item) {
		// All TextField
		item.setProductCode(CreateElementOnGui.getValueTextField(tfProductCode));
		item.setProductId(CreateElementOnGui.getValueTextField(tfProductId));
		item.setCommercialRef(CreateElementOnGui
				.getValueTextField(tfCommercialRef));
		item.setItemId(CreateElementOnGui.getValueTextField(tfItemId));
		item.setOrderShippingFeeValue(CreateElementOnGui
				.getValueTextField(tfOrderShippingFee));

		item.setOrderlineDiscountPercentage(CreateElementOnGui
				.getValueTextField(tfOrderlineDiscountPerc));
		item.setOrderlineDiscount(CreateElementOnGui
				.getValueTextField(tfOrderlineDiscount));

		item.setOrderProposeDiscountValue(CreateElementOnGui
				.getValueTextField(tfDiscount));

		item.setOrderlineSellingPriceValue(CreateElementOnGui
				.getValueTextField(tfSellingPrice));
		item.setFamily(CreateElementOnGui.getValueTextField(tfFamily));

		item.setCategory(CreateElementOnGui.getValueTextField(tfCategory));

		item.setShippingDiscountPercentValue(CreateElementOnGui
				.getValueTextField(tfShippingDiscountPercent));
		item.setOrderDiscountPercentValue(CreateElementOnGui
				.getValueTextField(tfOrderDiscountPercent));
	}

	public AdvantageItem getContentValues() {
		AdvantageItem item = new AdvantageItem();
		getContentValuesFromCheckBoxes(item);
		getContentValuesFromTextFields(item);
		getContentValueAdvantageWithAfm(item);

		return item;
	}

	private void setContentValuesForCheckBoxes(AdvantageItem item) {
		// All Checkboxs and Default is false if null
		chbGift.setValue(BooleanUtil.getValueWithoutNull(item.getGiftEnable()));

		chbOrderProposeDiscount.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderProposeDiscountEnable()));

		chbDiscountForCheapestRefco.setValue(BooleanUtil
				.getValueWithoutNull(item.getDiscountForCheapestRefcoEnable()));

		chbAddRefcoFromSalesupport.setValue(BooleanUtil
				.getValueWithoutNull(item.getAddRefcoFromSalesupportEnable()));

		chbAddRefcoOfOrder.setValue(BooleanUtil.getValueWithoutNull(item
				.getAddRefcoOfOrderEnable()));

		chbAddRefco.setValue(BooleanUtil.getValueWithoutNull(item
				.getAddRefcoEnable()));

		chbShippingDiscountPercent.setValue(BooleanUtil
				.getValueWithoutNull(item.getShippingDiscountPercentEnable()));

		chbOrderDiscountPercent.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderDiscountPercentEnable()));

		chbOrderShippingFee.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderShippingFeeEnable()));

		// Order Line
		chbOrderLineSellingPrice.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderlineSellingPriceEnable()));

		chbOrderlineDiscountPerc.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderlineDiscountPercentageEnable()));

		chbOrderlineDiscount.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderlineDiscountEnable()));

		chbOrderLineShippingFee.setValue(BooleanUtil.getValueWithoutNull(item
				.getOrderlineShippingFeeEnable()));

		chbOrderlineShippingFeesDiscountPerc.setValue(BooleanUtil
				.getValueWithoutNull(item
						.getOrderlineShippingFeeDiscountPercentageEnable()));

	}

	/**
	 * Set Language for OrderLine captions
	 */
	public void setOrderLineDiscountState(String priceType) {
		if (priceType.equals(DomainRule.PriceType.SELLING_PRICE.value())) {
			chbOrderlineDiscountPerc
					.setCaption(SessionData.getI18N().getMessage(
							Constants.ORDERLINE_SELLING_DISCOUNT_PERC_CHECKBOX));
			chbOrderlineDiscount.setCaption(SessionData.getI18N().getMessage(
					Constants.ORDERLINE_SELLING_DISCOUNT_CHECKBOX));
		} else if (priceType.equals(DomainRule.PriceType.REAL_PRICE.value())) {
			chbOrderlineDiscountPerc
					.setCaption(SessionData.getI18N().getMessage(
							Constants.ORDERLINE_REAL_DISCOUNT_PERC_CHECKBOX));
			chbOrderlineDiscount.setCaption(SessionData.getI18N().getMessage(
					Constants.ORDERLINE_REAL_DISCOUNT_CHECKBOX));
		} else {
			chbOrderlineDiscountPerc.setCaption(SessionData.getI18N()
					.getMessage(Constants.ORDERLINE_DISCOUNT_PERC_CHECKBOX));
			chbOrderlineDiscount.setCaption(SessionData.getI18N().getMessage(
					Constants.ORDERLINE_DISCOUNT_CHECKBOX));
		}
	}

	public void setVisibleOrderLineDiscountPerc(Boolean value) {
		if (!value) {
			advantageCustomLayout.removeComponent(chbOrderlineDiscountPerc);
			advantageCustomLayout.removeComponent(tfOrderlineDiscountPerc);
			chbOrderlineDiscountPerc.setValue(value);
			tfOrderlineDiscountPerc.setValue("");
		} else {
			advantageCustomLayout.addComponent(chbOrderlineDiscountPerc,
					"lcCbOrderlineDiscountPerc");
			advantageCustomLayout.addComponent(tfOrderlineDiscountPerc,
					"lcTfOrderlineDiscountPerc");
			chbOrderlineDiscountPerc.setValue(value);
		}
	}

	private void setContentValuesForTextFields(AdvantageItem item) {
		// All TextField
		tfProductCode.setValue(StringUtil.getValueWithoutNull(item
				.getProductCode()));

		tfProductId
				.setValue(StringUtil.getValueWithoutNull(item.getProductId()));

		tfCommercialRef.setValue(StringUtil.getValueWithoutNull(item
				.getCommercialRef()));

		tfItemId.setValue(StringUtil.getValueWithoutNull(item.getItemId()));

		tfOrderShippingFee.setValue(StringUtil.getValueWithoutNull(StringUtil
				.correctDoubleFieldFormat(item.getOrderShippingFeeValue())));

		tfDiscount
				.setValue(StringUtil.getValueWithoutNull(StringUtil
						.correctDoubleFieldFormat(item
								.getOrderProposeDiscountValue())));

		tfFamily.setValue(StringUtil.getValueWithoutNull(StringUtil
				.correctDoubleFieldFormat(item.getFamily())));

		tfFromSalesupportOffer.setValue(StringUtil.getValueWithoutNull(item
				.getFromSalesupportOffer()));

		tfCategory.setValue(StringUtil.getValueWithoutNull(item.getCategory()));

		tfOfOrderOffer.setValue(StringUtil.getValueWithoutNull(item
				.getOfOrderOffer()));

		tfRefco.setValue(StringUtil.getValueWithoutNull(item.getRefco()));

		tfShippingDiscountPercent.setValue(StringUtil
				.getValueWithoutNull(StringUtil.correctDoubleFieldFormat(item
						.getShippingDiscountPercentValue())));

		tfOrderDiscountPercent.setValue(StringUtil
				.getValueWithoutNull(StringUtil.correctDoubleFieldFormat(item
						.getOrderDiscountPercentValue())));

		// Order Line
		tfSellingPrice
				.setValue(StringUtil.getValueWithoutNull(StringUtil
						.correctDoubleFieldFormat(item
								.getOrderlineSellingPriceValue())));

		tfOrderlineDiscountPerc.setValue(StringUtil
				.getValueWithoutNull(StringUtil.correctDoubleFieldFormat(item
						.getOrderlineDiscountPercentage())));

		tfOrderlineDiscount.setValue(StringUtil.getValueWithoutNull(StringUtil
				.correctDoubleFieldFormat(item.getOrderlineDiscount())));

		tfOrderLineShippingFee.setValue(StringUtil
				.getValueWithoutNull(StringUtil.correctDoubleFieldFormat(item
						.getOrderlineShippingFeeValue())));

		tfOrderlineShippingDiscountPerc.setValue(StringUtil
				.getValueWithoutNull(StringUtil.correctDoubleFieldFormat(item
						.getOrderlineShippingFeeDiscountPercentage())));

	}

	public void setContentValues(AdvantageItem item) {
		reload();
		setContentValuesForCheckBoxes(item);
		setContentValuesForTextFields(item);

		setFieldEnable();

		validate();
	}

	@Override
	public void reload() {
		// All Checkbox
		chbGift.setValue(Boolean.FALSE);
		chbOrderShippingFee.setValue(Boolean.FALSE);
		chbOrderLineShippingFee.setValue(Boolean.FALSE);
		chbOrderProposeDiscount.setValue(Boolean.FALSE);
		chbOrderLineSellingPrice.setValue(Boolean.FALSE);
		chbDiscountForCheapestRefco.setValue(Boolean.FALSE);
		chbAddRefcoFromSalesupport.setValue(Boolean.FALSE);
		chbAddRefcoOfOrder.setValue(Boolean.FALSE);
		chbAddRefco.setValue(Boolean.FALSE);
		chbShippingDiscountPercent.setValue(Boolean.FALSE);
		chbOrderDiscountPercent.setValue(Boolean.FALSE);
		chbOrderlineDiscountPerc.setValue(Boolean.FALSE);
		chbOrderlineDiscount.setValue(Boolean.FALSE);
		chbOrderlineShippingFeesDiscountPerc.setValue(Boolean.FALSE);

		// All TextField
		tfProductCode.setValue("");
		tfProductId.setValue("");
		tfCommercialRef.setValue("");
		tfItemId.setValue("");
		tfOrderShippingFee.setValue("");
		tfOrderLineShippingFee.setValue("");
		tfDiscount.setValue("");
		tfSellingPrice.setValue("");
		tfFamily.setValue("");
		tfFromSalesupportOffer.setValue("");
		tfCategory.setValue("");
		tfOfOrderOffer.setValue("");
		tfRefco.setValue("");
		tfShippingDiscountPercent.setValue("");
		tfOrderDiscountPercent.setValue("");
		tfOrderlineDiscountPerc.setValue("");
		tfOrderlineShippingDiscountPerc.setValue("");
		tfCheapestFromFamilyDiscount.setValue("");
	}

	private ProductSelection getProductSelectionSearchItem() {
		ProductSelection ps = new ProductSelection();
		ps.setItemId((String) tfItemId.getValue());
		ps.setProductCode((String) tfProductCode.getValue());
		ps.setProductId((String) tfProductId.getValue());
		ps.setRefcoId((String) tfCommercialRef.getValue());
		ps.setCountryCode(parentView.getCountryCodeFromConditionView());
		ps.setLanguageCode(parentView.getLanguageCodeFromConditionView());
		ps.setBussines(parentView.getBusLineConditionView());
		return ps;
	}

	ProductSelectionPopup productSelectionPopup = null;

	@Override
	public void buttonClick(ClickEvent event) {
		final Button source = event.getButton();

		if (source == btnSave) {
			LOG.info(DateTimeUtil.getNow() + "Click save button");
			boolean success = validate();
			if (success) {
				if (parentView.isValidated()) {
					boolean saved = false;
//					IController<DomainRule, DomainRuleSearchItem, Long> promotionController = ControllerFactory
//							.getDomainRuleController();

					DomainRule domainRule = parentView.getCurrentDomainRule();
					String rulename = domainRule.getRuleName();
//					saved = promotionController.saveObject(domainRule);
					saved = BusinessFactory.getRuleBusiness().saveRule(domainRule, SessionData.getRoleName());
					if (saved) {
						getWindow().showNotification(
								rulename,
								SessionData.getI18N().getMessage(
										Constants.SUCCESSFULLY_MESSAGE),
								Notification.TYPE_WARNING_MESSAGE);
						parentView.showPromotionListView(Boolean.FALSE, Boolean.TRUE);
					} else {
						getWindow().showNotification(
								SessionData.getI18N().getMessage(
										Constants.FAILED_MESSAGE),
								Notification.TYPE_WARNING_MESSAGE);
					}
				} else {
					getWindow()
							.showNotification(
									SessionData
											.getI18N()
											.getMessage(
													Constants.NOTIFY_CONSTRAINT_ERROR_AT_CONDITION_VIEW),
									Notification.TYPE_WARNING_MESSAGE);
				}
			}

		} else if (source == btnCancel) {
			LOG.info(DateTimeUtil.getNow() + "Click cancel button");
			parentView.showPromotionListView(Boolean.FALSE, Boolean.TRUE);
		} else if (source == btnSelect) {
			LOG.info(DateTimeUtil.getNow()
					+ "Click select button. Show popup to fill in detail infomation");

			if (productSelectionPopup == null) {
				// Disable main view when using popup "select"
				if (this.getApplication().getContext() instanceof MainView) {
					((MainView) this.getApplication().getContext())
							.setEnabled(false);
				}

				// Show "select" popup
				final Window w = new Window();
				getApplication().getMainWindow().addWindow(w);
				ProductSelection selection = getProductSelectionSearchItem();

				productSelectionPopup = new ProductSelectionPopup(selection);
				productSelectionPopup.setSizeFull();
				productSelectionPopup.setCaption(SessionData.getI18N()
						.getMessage(Constants.PRODUCT_SELECTION_POPUP));

				w.addListener(new Window.CloseListener() {
					private static final long serialVersionUID = 1L;

					// Close-listener
					public void windowClose(CloseEvent e) {
						if (e.getSource() == w) {
							LOG.info(DateTimeUtil.getNow()
									+ "Get the row chosen to fill in form");

							ProductSelection p = productSelectionPopup
									.getProductSelection();
							if (p.getProductCode().isEmpty()
									&& p.getProductId().isEmpty()
									&& p.getItemId().isEmpty()
									&& p.getRefcoId().isEmpty()) {

								chbGift.setValue(Boolean.FALSE);
								tfProductCode.setEnabled(Boolean.FALSE);
								tfProductId.setEnabled(Boolean.FALSE);
								tfItemId.setEnabled(Boolean.FALSE);
								tfCommercialRef.setEnabled(Boolean.FALSE);

								tfProductCode.setValue("");
								tfProductId.setValue("");
								tfItemId.setValue("");
								tfCommercialRef.setValue("");

							} else {
								chbGift.setValue(Boolean.TRUE);
								tfProductCode.setEnabled(Boolean.TRUE);
								tfProductId.setEnabled(Boolean.TRUE);
								tfItemId.setEnabled(Boolean.TRUE);
								tfCommercialRef.setEnabled(Boolean.TRUE);

								tfProductCode.setValue(p.getProductCode());
								tfProductId.setValue(p.getProductId());
								tfItemId.setValue(p.getItemId());
								tfCommercialRef.setValue(p.getRefcoId());
								parentView.setCountryCodeFromConditionView(p
										.getCountryCode());

							}
							productSelectionPopup = null;
						}
					}
				});
				w.setContent(productSelectionPopup);
				w.setWidth(800, Window.UNITS_PIXELS);
				w.setHeight(660, Window.UNITS_PIXELS);
				w.center();
			}

		} else if (source == chbGift) {
			CreateElementOnGui.setFieldsEnable((CheckBox) source,
					tfProductCode, tfProductId, tfCommercialRef, tfItemId);

		} else if (source == chbOrderShippingFee) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOrderShippingFee);

		} else if (source == chbShippingDiscountPercent) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfShippingDiscountPercent);

		} else if (source == chbOrderDiscountPercent) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOrderDiscountPercent);

		} else if (source == chbOrderLineShippingFee) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOrderLineShippingFee);

		} else if (source == chbOrderProposeDiscount) {
			CreateElementOnGui
					.setTextFieldEnable((CheckBox) source, tfDiscount);
			// CreateElementOnGui.setSelectBoxEnable((CheckBox) source,
			// cbbPriceType);

		} else if (source == chbOrderLineSellingPrice) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfSellingPrice);

		} else if (source == chbOrderlineDiscountPerc) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOrderlineDiscountPerc);

		} else if (source == chbOrderlineDiscount) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOrderlineDiscount);

		} else if (source == chbOrderlineShippingFeesDiscountPerc) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOrderlineShippingDiscountPerc);

		} else if (source == chbDiscountForCheapestRefco) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source, tfFamily);

		} else if (source == chbAddRefcoFromSalesupport) {
			CreateElementOnGui.setFieldsEnable((CheckBox) source,
					tfFromSalesupportOffer, tfCategory);

		} else if (source == chbAddRefcoOfOrder) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source,
					tfOfOrderOffer);

		} else if (source == chbAddRefco) {
			CreateElementOnGui.setTextFieldEnable((CheckBox) source, tfRefco);
		}
	}

	/**
	 * This is the function create layout of advantage view
	 */
	@AutoGenerated
	private void buildMainLayout() {
		buildGeneralEnvironment();
		buildGeneralGift();
		buildGeneralShipping();
		buildGeneralOrder();
		buildControlVerticalLayout();
	}

	/**
	 * This is the function create label of advantage view.
	 */
	@AutoGenerated
	private void buildGeneralEnvironment() {
		// lblEnvironmentName
		lblEnvironmentName = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), advantageCustomLayout,
				"lblEnv", null);

		// lblBusiness
		lblBusiness = new Label();
		lblBusiness.setImmediate(false);
		lblBusiness.setValue("Business:");
		// lblRule
		lblRule = new Label();
		lblRule.setImmediate(false);
		lblRule.setValue("Rule:");
		// lblBusinessLine
		lblBusinessLine = new Label();
		lblBusinessLine.setImmediate(false);
		// lblRuleName
		lblRuleName = new Label();
		lblRuleName.setImmediate(false);
		lblRuleName.setValue("DISCOUNT-50");
	}

	/**
	 * This is the function create region gift of advantage view
	 */
	@AutoGenerated
	private void buildGeneralGift() {
		lblGift = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), advantageCustomLayout,
				"lblGift", null);
		chbGift = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbGift");
		tfCommercialRef = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				advantageCustomLayout, "lcCommercialRef");
		tfItemId = CreateElementOnGui.createIntegerField(advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcItemID");
		tfProductId = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				advantageCustomLayout, "lcProductID");
		tfProductCode = CreateElementOnGui.createTexboxPosition(
				StyleNameCss.INLINE_FILED.getStyleName(),
				advantageCustomLayout, "lcProductCode");
		// btnSelect
		btnSelect = CreateElementOnGui.createNativeButtonPosition(
				StyleNameCss.SMALL_BUTTON.getStyleName(),
				advantageCustomLayout, "lcBtnSelect", "Select");
	}

	/**
	 * Hide toolbar with Bussines is Afm
	 * 
	 * @param String
	 */
	private void setAdvantageDisplay(String bussines) {
		if (bussines.equals(Constants.AFM_BUSSINES_LINE)) {
			chbOrderLineShippingFee.setVisible(false);
			tfOrderLineShippingFee.setVisible(false);

			chbOrderlineShippingFeesDiscountPerc.setVisible(false);
			tfOrderlineShippingDiscountPerc.setVisible(false);

			chbAddRefcoFromSalesupport.setVisible(false);
			tfFromSalesupportOffer.setVisible(false);

			chbAddRefcoFromSalesupport.setVisible(false);
			tfFromSalesupportOffer.setVisible(false);

			chbAddRefcoOfOrder.setVisible(false);
			tfOfOrderOffer.setVisible(false);

			chbAddRefco.setVisible(false);
			tfRefco.setVisible(false);

		} else {
			chbOrderLineShippingFee.setVisible(true);
			tfOrderLineShippingFee.setVisible(true);

			chbOrderlineShippingFeesDiscountPerc.setVisible(true);
			tfOrderlineShippingDiscountPerc.setVisible(true);

			chbAddRefcoFromSalesupport.setVisible(true);
			tfFromSalesupportOffer.setVisible(true);

			chbAddRefcoFromSalesupport.setVisible(true);
			tfFromSalesupportOffer.setVisible(true);

			chbAddRefcoOfOrder.setVisible(true);
			tfOfOrderOffer.setVisible(true);

			chbAddRefco.setVisible(true);
			tfRefco.setVisible(true);

		}
	}

	/**
	 * This is the function create region shipping of advantage view
	 */
	@AutoGenerated
	private void buildGeneralShipping() {
		lblShipping = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), advantageCustomLayout,
				"lblShipping", null);
		chbOrderLineSellingPrice = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbOrderLineSellingPrice");
		tfSellingPrice = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"lcTfOrderLineSellingPrice");
		chbOrderLineShippingFee = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbOrderLineShippingFee");
		tfOrderLineShippingFee = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"lcTfOrderLineShippingFee");

		chbOrderlineDiscountPerc = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbOrderlineDiscountPerc");
		tfOrderlineDiscountPerc = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"lcTfOrderlineDiscountPerc");

		chbOrderlineDiscount = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbOrderlineDiscount");
		tfOrderlineDiscount = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"lcTfOrderlineDiscount");

		chbOrderlineShippingFeesDiscountPerc = CreateElementOnGui
				.createCheckBox(null, StyleNameCss.INLINE_BOX.getStyleName(),
						advantageCustomLayout,
						"chbOrderlineShippingFeesDiscountPerc");
		tfOrderlineShippingDiscountPerc = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"tfOrderlineShippingDiscountPerc");
	}

	/**
	 * This is the function create region order of advantage view
	 */
	@AutoGenerated
	private void buildGeneralOrder() {
		lblOrder = CreateElementOnGui.createLabelPosition(
				StyleNameCss.INLINE.getStyleName(), advantageCustomLayout,
				"lblOrder", null);
		chbOrderProposeDiscount = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbOrderProposeDiscount");
		tfDiscount = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"lcTfOrderProposeDiscount");
		chbOrderDiscountPercent = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"chbOrderDiscountPercent");
		tfOrderDiscountPercent = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"tfOrderDiscountPercent");
		chbOrderShippingFee = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbOrderShippingFee");
		tfOrderShippingFee = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"lcTfOrderShippingFee");
		chbShippingDiscountPercent = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"chbShippingDiscountPercent");
		tfShippingDiscountPercent = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"tfShippingDiscountPercent");
		chbDiscountForCheapestRefco = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"lcCbDiscountForCheapestRefco");
		tfFamily = CreateElementOnGui.createDoubleField(advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "lcTfFamily");
		chbAddRefcoFromSalesupport = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"chbAddRefcoFromSalesupport");
		tfFromSalesupportOffer = CreateElementOnGui.createIntegerField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(),
				"tfFromSalesupportOffer");
		chbAddRefcoOfOrder = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"chbAddRefcoOfOrder");
		tfOfOrderOffer = CreateElementOnGui.createIntegerField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfOfOrderOffer");
		chbAddRefco = CreateElementOnGui.createCheckBox(null,
				StyleNameCss.INLINE_BOX.getStyleName(), advantageCustomLayout,
				"chbAddRefco");
		tfRefco = CreateElementOnGui.createIntegerField(advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), "tfRefco");
		tfCategory = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), null);
		tfCheapestFromFamilyDiscount = CreateElementOnGui.createDoubleField(
				advantageCustomLayout,
				StyleNameCss.INLINE_FILED.getStyleName(), null);
	}

	/**
	 * This is function create region button control of advantage view
	 */
	@AutoGenerated
	private void buildControlVerticalLayout() {

		// btnSave
		btnSave = CreateElementOnGui.createNativeButtonPosition(
				StyleNameCss.BUTTON_STYLE.getStyleName(),
				advantageCustomLayout, "lcBtnSaveChange", "");

		// btnCancel
		btnCancel = CreateElementOnGui.createNativeButtonPosition(
				StyleNameCss.RIGHT_BUTTON.getStyleName(),
				advantageCustomLayout, "lcBtnCancel", "");
		btnCancel.addStyleName("cancel");

		advantageCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.CANCEL_BUTTON)), "tipCancel");
	}

	private void getContentValueAdvantageWithAfm(AdvantageItem item) {
		if (lblBusinessLine.getValue().equals(Constants.AFM_BUSSINES_LINE)) {
			item.setOrderlineShippingFeeValue(null);
			item.setOrderlineShippingFeeDiscountPercentage(null);
			item.setFromSalesupportOffer(null);
			item.setOfOrderOffer(null);
			item.setRefco(null);

		} else {
			item.setOrderlineShippingFeeValue(CreateElementOnGui
					.getValueTextField(tfOrderLineShippingFee));

			item.setOrderlineShippingFeeDiscountPercentage(CreateElementOnGui
					.getValueTextField(tfOrderlineShippingDiscountPerc));

			item.setFromSalesupportOffer(CreateElementOnGui
					.getValueTextField(tfFromSalesupportOffer));

			item.setOfOrderOffer(CreateElementOnGui
					.getValueTextField(tfOfOrderOffer));
			item.setRefco(CreateElementOnGui.getValueTextField(tfRefco));

		}
	}
}
